/**
 * 语音识别测试脚本
 * 用于验证Vosk集成是否正常工作
 */

import SpeechRecognizer from './SpeechRecognizer.js'

class SpeechRecognitionTester {
  constructor() {
    this.speechRecognizer = null
    this.testResults = []
  }

  /**
   * 运行所有测试
   */
  async runAllTests() {
    console.log('开始语音识别测试...')

    try {
      // 测试1: 初始化测试
      await this.testInitialization()

      // 测试2: 模型加载测试
      await this.testModelLoading()

      // 测试3: 音频处理测试
      await this.testAudioProcessing()

      // 测试4: 资源清理测试
      await this.testCleanup()

      console.log('所有测试完成')
      this.printTestResults()
    } catch (error) {
      console.error('测试过程中发生错误:', error)
    }
  }

  /**
   * 测试初始化功能
   */
  async testInitialization() {
    console.log('\n=== 测试1: 初始化测试 ===')

    try {
      this.speechRecognizer = new SpeechRecognizer()

      // 测试基本属性
      const hasRequiredProperties =
        this.speechRecognizer.recognizer === null &&
        this.speechRecognizer.isRecognizing === false &&
        this.speechRecognizer.recognitionResults.length === 0

      if (hasRequiredProperties) {
        this.addTestResult('初始化', 'PASS', 'SpeechRecognizer实例创建成功')
      } else {
        this.addTestResult('初始化', 'FAIL', 'SpeechRecognizer实例属性不正确')
      }
    } catch (error) {
      this.addTestResult('初始化', 'ERROR', `初始化失败: ${error.message}`)
    }
  }

  /**
   * 测试模型加载功能
   */
  async testModelLoading() {
    console.log('\n=== 测试2: 模型加载测试 ===')

    if (!this.speechRecognizer) {
      this.addTestResult('模型加载', 'SKIP', 'SpeechRecognizer未初始化')
      return
    }

    try {
      // 测试初始化方法（不实际加载模型）
      const result = await this.speechRecognizer.initialize({
        modelPath: '/models/vosk-model-small-cn-0.22',
        onProgress: (progress) => console.log('进度:', progress),
        onResult: (result) => console.log('结果:', result),
        onError: (error) => console.log('错误:', error),
        onComplete: (complete) => console.log('完成:', complete),
      })

      if (result === false) {
        this.addTestResult('模型加载', 'PASS', '模型加载测试完成（预期失败，因为模型文件不存在）')
      } else {
        this.addTestResult('模型加载', 'PASS', '模型加载成功')
      }
    } catch (error) {
      this.addTestResult('模型加载', 'PASS', `模型加载测试完成: ${error.message}`)
    }
  }

  /**
   * 测试音频处理功能
   */
  async testAudioProcessing() {
    console.log('\n=== 测试3: 音频处理测试 ===')

    if (!this.speechRecognizer) {
      this.addTestResult('音频处理', 'SKIP', 'SpeechRecognizer未初始化')
      return
    }

    try {
      // 测试音频格式转换
      const testFloat32Array = new Float32Array([0.1, -0.2, 0.3, -0.4, 0.5])
      const int16Array = this.speechRecognizer.convertToInt16(testFloat32Array)

      if (int16Array instanceof Int16Array && int16Array.length === testFloat32Array.length) {
        this.addTestResult('音频格式转换', 'PASS', 'Float32Array转Int16Array成功')
      } else {
        this.addTestResult('音频格式转换', 'FAIL', '音频格式转换失败')
      }

      // 测试结果合并
      const testResults = [
        { text: '你好', confidence: 0.8, timestamp: Date.now() - 2000 },
        { text: '世界', confidence: 0.9, timestamp: Date.now() - 1000 },
        { text: '测试', confidence: 0.7, timestamp: Date.now() },
      ]

      const mergedText = this.speechRecognizer.mergeResults(testResults)
      if (mergedText === '你好 世界 测试') {
        this.addTestResult('结果合并', 'PASS', '识别结果合并成功')
      } else {
        this.addTestResult('结果合并', 'FAIL', `结果合并失败，期望: '你好 世界 测试'，实际: '${mergedText}'`)
      }
    } catch (error) {
      this.addTestResult('音频处理', 'ERROR', `音频处理测试失败: ${error.message}`)
    }
  }

  /**
   * 测试资源清理功能
   */
  async testCleanup() {
    console.log('\n=== 测试4: 资源清理测试 ===')

    if (!this.speechRecognizer) {
      this.addTestResult('资源清理', 'SKIP', 'SpeechRecognizer未初始化')
      return
    }

    try {
      this.speechRecognizer.destroy()

      // 检查清理后的状态
      const isCleaned =
        this.speechRecognizer.recognizer === null &&
        this.speechRecognizer.model === null &&
        this.speechRecognizer.recognitionResults.length === 0 &&
        this.speechRecognizer.isRecognizing === false

      if (isCleaned) {
        this.addTestResult('资源清理', 'PASS', '资源清理成功')
      } else {
        this.addTestResult('资源清理', 'FAIL', '资源清理不完整')
      }
    } catch (error) {
      this.addTestResult('资源清理', 'ERROR', `资源清理失败: ${error.message}`)
    }
  }

  /**
   * 添加测试结果
   */
  addTestResult(testName, status, message) {
    this.testResults.push({
      test: testName,
      status: status,
      message: message,
      timestamp: new Date().toISOString(),
    })

    const statusEmoji = {
      PASS: '✅',
      FAIL: '❌',
      ERROR: '⚠️',
      SKIP: '⏭️',
    }

    console.log(`${statusEmoji[status]} ${testName}: ${message}`)
  }

  /**
   * 打印测试结果摘要
   */
  printTestResults() {
    console.log('\n=== 测试结果摘要 ===')

    const summary = {
      total: this.testResults.length,
      pass: this.testResults.filter((r) => r.status === 'PASS').length,
      fail: this.testResults.filter((r) => r.status === 'FAIL').length,
      error: this.testResults.filter((r) => r.status === 'ERROR').length,
      skip: this.testResults.filter((r) => r.status === 'SKIP').length,
    }

    console.log(`总测试数: ${summary.total}`)
    console.log(`通过: ${summary.pass}`)
    console.log(`失败: ${summary.fail}`)
    console.log(`错误: ${summary.error}`)
    console.log(`跳过: ${summary.skip}`)

    if (summary.fail > 0 || summary.error > 0) {
      console.log('\n失败的测试:')
      this.testResults
        .filter((r) => r.status === 'FAIL' || r.status === 'ERROR')
        .forEach((r) => {
          console.log(`  - ${r.test}: ${r.message}`)
        })
    }

    if (summary.pass === summary.total) {
      console.log('\n🎉 所有测试通过！')
    } else {
      console.log('\n⚠️ 部分测试失败，请检查相关功能')
    }
  }
}

// 如果直接运行此脚本
if (typeof window !== 'undefined') {
  // 在浏览器环境中运行
  window.SpeechRecognitionTester = SpeechRecognitionTester

  // 自动运行测试
  const tester = new SpeechRecognitionTester()
  tester.runAllTests()
} else {
  // 在Node.js环境中导出
  module.exports = SpeechRecognitionTester
}
